import type { Router, RouteRecordRaw } from 'vue-router';
import { usePermissionStoreWithOut } from '/@/store/modules/permission';
import { RootRoute } from '/@/router/routes';
import { PageEnum } from '/@/enums/pageEnum';
import { useUserStoreWithOut } from '/@/store/modules/user';
import { PAGE_NOT_FOUND_ROUTE } from '/@/router/routes/basic';
const ROOT_PATH = RootRoute.path;
const HOME_PATH = PageEnum.BASE_HOME;
const LOGIN_PATH = PageEnum.BASE_LOGIN;
const MOD_PWD_PAGE = PageEnum.MOD_PWD_PAGE;
const BASE_HOME_ANALYSIS = PageEnum.BASE_HOME_ANALYSIS;

// 白名单路由列表，无需权限即可访问的页面
const whitePathList: PageEnum[] = [LOGIN_PATH, MOD_PWD_PAGE, BASE_HOME_ANALYSIS];

const ROUTE_BUILDING_KEY = 'ROUTE_BUILDING';

export function createPermissionGuard(router: Router) {
  const userStore = useUserStoreWithOut();
  const permissionStore = usePermissionStoreWithOut();
  router.beforeEach(async (to, from, next) => {
    if (
      from.path === ROOT_PATH &&
      to.path === HOME_PATH &&
      userStore.getUserInfo.homePath &&
      userStore.getUserInfo.homePath !== HOME_PATH
    ) {
      next(userStore.getUserInfo.homePath);
      return;
    }

    // const token = userStore.getToken;
    const token = !userStore.getSessionTimeout;

    // // 404页面：立即重定向到首页
    // if (to.name === PAGE_NOT_FOUND_ROUTE.name) {
    //   next(HOME_PATH);
    //   return;
    // }

    // Whitelist can be directly entered
    if (whitePathList.includes(to.path as PageEnum)) {
      // console.log(to.path);
      // if (to.path === LOGIN_PATH && token) {
      //   const isSessionTimeout = userStore.getSessionTimeout;
      //   try {
      //     await userStore.afterLoginAction();
      //     if (!isSessionTimeout) {
      //       next((to.query?.redirect as string) || '/');
      //       return;
      //     }
      //   } catch {}
      // }
      if (to.path === MOD_PWD_PAGE) {
        try {
          await userStore.getUserInfoAction();
        } catch (error: any) {
          console.error(error);
        }
      }
      // if (to.path === MOD_PWD_PAGE) {
      //   try {
      //     await userStore.getUserInfoAction();
      //   } catch (error: any) {
      //     console.error(error);
      //   }
      // }
      next();
      return;
    }

    // force modify password
    if (userStore.getPageCacheByKey('modifyPasswordMsg')) {
      next({
        path: MOD_PWD_PAGE,
        replace: true,
      });
      return;
    }

    // token does not exist
    if (!token) {
      // You can access without permission. You need to set the routing meta.ignoreAuth to true
      if (to.meta.ignoreAuth) {
        next();
        return;
      }

      // redirect login page
      const redirectData: { path: string; replace: boolean; query?: Recordable<string> } = {
        path: LOGIN_PATH,
        replace: true,
      };
      if (to.path) {
        redirectData.query = {
          ...redirectData.query,
          redirect: to.path,
        };
      }
      next(redirectData);
      return;
    }

    // Jump to the 404 page after processing the login
    if (
      from.path === LOGIN_PATH &&
      to.name === PAGE_NOT_FOUND_ROUTE.name &&
      to.fullPath !== (userStore.getUserInfo.homePath || HOME_PATH)
    ) {
      next(userStore.getUserInfo.homePath || HOME_PATH);
      return;
    }

    // get userinfo while last fetch time is empty
    if (userStore.getLastUpdateTime === 0) {
      try {
        await userStore.getUserInfoAction();
      } catch (error: any) {
        // const err: string = error?.toString?.() ?? '';
        // if (
        //   from.fullPath === '/' &&
        //   ((error?.code === 'ECONNABORTED' && err.indexOf('timeout of') !== -1) ||
        //     err.indexOf('Network Error') !== -1)
        // ) {
        //   next(LOGIN_PATH);
        //   return;
        // }
        let path = LOGIN_PATH as string;
        if (to.path !== '/' && to.path !== LOGIN_PATH) {
          path = path + '?redirect=' + to.fullPath;
        }
        next(path);
        return;
      }
    }

    // 检查是否已动态添加路由
    if (permissionStore.getIsDynamicAddedRoute) {
      // 确保路由已完全加载
      if (router.hasRoute(to.name as string)) {
        next();
      } else {
        // 路由可能还未注册完成，等待一下再尝试
        setTimeout(() => {
          next({ ...to, replace: true });
        }, 100);
      }
      return;
    }

    // 防止重复构建路由
    const isBuilding = localStorage.getItem(ROUTE_BUILDING_KEY);
    if (isBuilding === 'true') {
      // 等待路由构建完成
      let checkCount = 0;
      const maxCheckCount = 50; // 最多检查50次(5秒)
      const checkInterval = setInterval(() => {
        checkCount++;
        
        if (permissionStore.getIsDynamicAddedRoute) {
          clearInterval(checkInterval);
          const redirectPath = (from.query.redirect || to.path) as string;
          const redirect = decodeURIComponent(redirectPath);
          // 确保路由存在再跳转
          if (router.hasRoute(to.name as string)) {
            const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect };
            next(nextData);
          } else {
            // 如果路由不存在，等待一下再重试
            setTimeout(() => {
              next({ path: redirect, replace: true });
            }, 100);
          }
        } else if (checkCount >= maxCheckCount) {
          // 超时处理
          clearInterval(checkInterval);
          localStorage.removeItem(ROUTE_BUILDING_KEY);
          console.error('等待路由构建超时');
          next('/login');
        }
      }, 100);
      return;
    }

  // 设置路由构建中标记
    localStorage.setItem(ROUTE_BUILDING_KEY, 'true');
    
    try {
      const routes = await permissionStore.buildRoutesAction();
      console.log('动态路由构建完成，路由数量:', routes.length);

      // 添加路由
      routes.forEach((route) => {
        const routeName = route.name;
        if (!router.hasRoute(routeName)) {
          router.addRoute(route as unknown as RouteRecordRaw);
          console.log('添加路由:', routeName);
        }
      });

      // 添加404路由
      if (!router.hasRoute(PAGE_NOT_FOUND_ROUTE.name)) {
        router.addRoute(PAGE_NOT_FOUND_ROUTE as unknown as RouteRecordRaw);
      }

      // 标记路由已添加完成
      permissionStore.setDynamicAddedRoute(true);
      console.log('路由已动态添加完成');

      // 清理构建标记
      localStorage.removeItem(ROUTE_BUILDING_KEY);

      // 处理重定向
      if (to.name === PAGE_NOT_FOUND_ROUTE.name) {
        // 动态添加路由后，重定向到fullPath
        next({ path: to.fullPath, replace: true, query: to.query });
      } else {
        const redirectPath = (from.query.redirect || to.path) as string;
        const redirect = decodeURIComponent(redirectPath);
        // 确保路由存在再跳转
        if (router.hasRoute(to.name as string)) {
          const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect };
          next(nextData);
        } else {
          // 如果路由不存在，等待一下再重试
          setTimeout(() => {
            next({ path: redirect, replace: true });
          }, 100);
        }
      }
    } catch (error) {
      console.error('构建动态路由失败:', error);
      // 清理构建标记
      localStorage.removeItem(ROUTE_BUILDING_KEY);
      // 重定向到登录页
      next('/login');
    }
  });
}
